<%layout("/eova/layout/dialog.html",{'title' : '查找数据'}){%>

<body class="easyui-layout">
	<div id="layoutNorth" region="north" split="true" style="height: 40px;">
		<form id="queryFindForm" onsubmit="return false;">
			<div id="eova-query" class="eova-form">
				<div class="eova-form-field" title="cn[title]">
					<div class="eova-form-lbl">档案名称:</div>
					<div>
						<div class="eova-text" id="title" name="query_title" value=""
							data-options=""></div>
					</div>
				</div>
			</div>
		</form>
		<script>
			var x = $("#eova-query").width();
			console.log(x);
			var max = parseInt(x / 290);
			console.log('每行最多能显示：' + max);
			if (max != 0) {
				var count = 1;
				var zs = parseInt(count / max);
				var ys = count % max;
				if (ys > 0) {
					zs++;
				}
				// 计算完整显示所需高度
				var y = 40 + 25 * zs;
				$("#eova-query").parent().parent().css("height", y + "px");
				//console.log('ys'+ ys);
				//console.log('共需：'+ zs);
				//console.log('height：'+ y);
			}

			$('div[class="eova-text"]').eovatext();
			$('div[class="eova-time"]').eovatime();
			$('div[class="eova-combo"]').eovacombo();
			$('div[class="eova-find"]').eovafind();
		</script>
	</div>
	<div data-options="region:'center',fit:false,border:false">
		<div id="toolbar">
			<table>
				<tr>
					<td><a href="javascript:void(0);" class="easyui-linkbutton"
						data-options="iconCls:'icon-zoom',plain:true" onclick="queryFun()">查询</a></td>
					<td><a href="javascript:void(0);" class="easyui-linkbutton"
						data-options="iconCls:'icon-arrowrefresh',plain:true"
						onclick="resetFun()">清除条件</a></td>
				</tr>
			</table>
		</div>
		<script type="text/javascript">
			// 回车自动查询
			$(document).keypress(function(e) {
				// 回车键事件 
				if (e.which == 13) {
					queryFun();
				}
			});

			// 重载Grid
			var queryFun = function() {
				$('#findGrid').datagrid('load',
						$.getFormParasObj($('#queryFindForm')));
			};
			// 刷新Grid
			var resetFun = function() {
				$('#queryFindForm input').val('');
				$('#findGrid').datagrid('load', {});
			};
		</script>
		
		
		<table id="findGrid" width="auto" height="auto"></table>
		<script>
			// var $findGrid;
			$(function() {

				// init param
				var id = "findGrid";
				var masterId = "";
				var $grid = $("#" + id);
				var $masterGrid;
				if (masterId != "") {
					$masterGrid = $("#" + masterId);
				}

				var menuCode = '';// medaobject code
				var objectCode = '';// medaobject code
				var toolbar = '';// grid ref toolbar
				var isPaging = eval('true');// is show pagination
				var url = '/attachment/findJson?code=ATTACHMENT&field=file_id';

				var objectJson = '{"biz_intercept":null,"cn":"title","code":"meta_template",\
									"data_source":"main","default_order":null,"diy_card":null,\
									"diy_js":null,"filter":null,"id":1,"is_celledit":false,\
									"is_first_load":true,"is_show_num":true,"is_single":true,\
									"name":"","pk_name":"id","table_name":"eova_template","view_name":null}';

				var fieldsJson = '[{"cn":"ID","config":null,"data_type":"string","defaulter":null,\
									"en":"id","exp":null,"formatter":null,"height":20,"id":1,\
									"is_add":true,"is_auto":true,"is_disable":false,"is_edit":false,\
									"is_multiple":false,"is_order":true,"is_query":false,"is_required":true,\
									"is_show":true,"is_update":true,"object_code":"eova_object_code",\
									"order_num":1,"placeholder":null,"po_code":null,"type":"文本框",\
									"validator":null,"width":50},\
									{"cn":"机构码","config":null,"data_type":"string","defaulter":null,\
										"en":"brchcd","exp":null,"formatter":null,"height":20,"id":1,\
										"is_add":true,"is_auto":true,"is_disable":false,"is_edit":false,\
										"is_multiple":false,"is_order":true,"is_query":false,"is_required":true,\
										"is_show":true,"is_update":true,"object_code":"eova_object_code",\
										"order_num":1,"placeholder":null,"po_code":null,"type":"文本框",\
									"validator":null,"width":100},\
									{"cn":"归档年度","config":null,"data_type":"string","defaulter":null,\
										"en":"file_year","exp":null,"formatter":null,"height":20,"id":1,\
										"is_add":true,"is_auto":true,"is_disable":false,"is_edit":false,\
										"is_multiple":false,"is_order":true,"is_query":false,"is_required":true,\
										"is_show":true,"is_update":true,"object_code":"eova_object_code",\
										"order_num":1,"placeholder":null,"po_code":null,"type":"文本框",\
									"validator":null,"width":80},\
									{"cn":"档案名称","config":null,"data_type":"string","defaulter":null,"en":"title",\
									"exp":null,"formatter":null,"height":20,"id":1,"is_add":true,"is_auto":true,\
									"is_disable":false,"is_edit":false,"is_multiple":false,"is_order":true,\
									"is_query":true,"is_required":true,"is_show":true,"is_update":true,\
									"object_code":"eova_object_code","order_num":2,"placeholder":null,\
									"po_code":null,"type":"文本框","validator":null,"width":500}]';

				var configJson = '';// config is json

				if (url == '') {
					url = '/grid/query/' + objectCode;
					if (menuCode != '') {
						url = url + '-' + menuCode;
					}
				}
				var paras = $.getUrlParas();
				// 是否含有关联查询条件
				if (paras && paras.indexOf('query_') != -1) {
					url = url + '?' + paras;
				}

				// console.log(objectCode + 'isFirstLoad' + isFirstLoad);

				var config, object, fields;

				if (configJson != '') {
					config = JSON.parse(configJson);
				}
				if (objectJson != '') {
					object = JSON.parse(objectJson);
				} else {
					$.syncGetJson('/meta/object/' + objectCode, function(json) {
						object = json;
					});
				}
				if (fieldsJson != '') {
					fields = JSON.parse(fieldsJson);
				} else {
					$.syncGetJson('/meta/fields/' + objectCode, function(json) {
						fields = json;
					});
				}
				//console.log(object);
				//console.log(fields);

				// 当前对象是否允许初始加载数据
				var isFirstLoad = false;
				var isFirstLoadNow = eval('true');
				// 必须当前业务和对象都允许加载数据
				if (isFirstLoadNow && object.is_first_load) {
					isFirstLoad = true;
				}

				var cols = [];
				var validators = {};
				// 批量选择框
				if (!object.is_single) {
					var attr = new Object;
					attr.field = 'ck';
					attr.checkbox = true;
					cols.push(attr);
				}
				// 字段属性
				$.each(fields,
						function(i, f) {
							if (!f.is_show) {
								// continue;
								return true;
							}

							var attr = new Object;
							attr.field = f.en;
							attr.title = f.cn;
							attr.width = f.width ? f.width : 150;

							if (f.is_order) {
								attr.sortable = true;
							}

							if (f.formatter != null) {
								attr.formatter = new Function('return '
										+ f.formatter)();
							} else {
								// 默认格式化处理
								if (f.type == '复选框') {
									attr.align = 'center';
									attr.formatter = function(value, row,
											index, field) {
										var ck = '<span class="ck0">□</span>';
										if (value) {
											ck = '<span class="ck1">☑</span>';
										}
										return ck;
									};
								}
								if (f.type == '文本框' || f.type == '编辑框'
										|| f.type == '文本域') {
									attr.formatter = function(value, row,
											index, field) {
										if (value && value.length > 10) {
											//alert($.encodeHtml(value));
											return '<span title=\"'
													+ $.encodeHtml(value)
													+ '\">'
													+ $.encodeHtml(value)
													+ '</span>'
										}
										return value;
									}
								}
							}
							// Grid Cell Editor,对象和字段允许行内编辑自增，自增长禁止编辑
							if (object.is_celledit && f.is_edit) {
								if (object.is_auto && object.is_auto == true) {
									return;
								}
								var editor = new Object;
								editor.type = f.editor;
								// 构造参数
								editor.options = {};
								if (f.type == '下拉框') {
									editor.options = {
										url : '/widget/comboJson/' + objectCode
												+ '-' + f.en,
										valueField : 'id',
										textField : 'cn',
										multiple : f.is_multiple
									}
								} else if (f.type == '查找框') {
									editor.options = {
										url : '/widget/find?code=' + objectCode
												+ '&field=' + f.en
												+ '&multiple=' + f.is_multiple

									}
								} else if (f.type == '日期框') {
									editor.options = {
										format : 'yyyy-MM-dd'
									}
								}
								editor.options['name'] = f.en;

								attr.editor = editor;

								// validator
								var rule = '';
								if (f.is_required) {
									rule = f.cn + ':required;';
								}
								if (f.validator) {
									rule = rule + f.validator;
								}
								if (rule != '') {
									validators[f.en] = {
										rule : rule
									};
								}
							}

							cols.push(attr);
						});

				console.log(cols);

				// 默认排序
				var sortName = null, sortOrder = 'asc';
				if (object.default_order) {
					var defaultOrder = object.default_order.split(' ');
					sortName = defaultOrder[0];
					if (defaultOrder.length > 1) {
						sortOrder = defaultOrder[1];
					}
				}

				var selectIndex;
				var $myGrid = $grid.datagrid({
					fit : true,
					border : false,
					striped : true,
					align : 'right',
					autoRowHeight : true,
					collapsible : false,
					remoteSort : true,
					multiSort : false,
					rownumbers : object.is_show_num,
					showFooter : true,

					ctrlSelect : true,
					singleSelect : object.is_single,

					toolbar : toolbar ? '#' + toolbar : null,
					pagination : isPaging,
					pageSize : 15,
					pageList : [ 15, 30, 50, 100, 200, 500, 1000, 2000 ],

					idField : object.pk_name,
					sortName : sortName,
					sortOrder : sortOrder,

					url : url,
					method : 'post',
					columns : [ cols ],
					// frozenColumns: [[{field:'diy_fun',title:'操作'}]],

					onHeaderContextMenu : function(e, field) {
						e.preventDefault();
						if (!cmenu) {
							createColumnMenu();
						}
						cmenu.menu('show', {
							left : e.pageX,
							top : e.pageY
						});
					},
					onBeforeLoad : function() {
						// 阻止初始化加载数据
						if (!isFirstLoad) {
							isFirstLoad = true;
							return false;
						}
					},
					onLoadSuccess : function(data) {
						if (object.is_celledit && data.total < 1) {
							// 暂时禁用，初始化不加载空行，使用Grid 分页栏按钮添加！
							$myGrid.datagrid('insertRow', {
								index : 0,
								row : {}
							});
						}
					},
					onRowContextMenu : function(e, rowIndex, rowData) {
						e.preventDefault();
						if (!rowMenu) {
							createRowMenu();
						}
						selectIndex = rowIndex;
						rowMenu.menu('show', {
							left : e.pageX,
							top : e.pageY
						});
					}
				});

				//     $findGrid = $myGrid;

				// 开启编辑模式
				if (object.is_celledit) {
					$myGrid.datagrid('enableCellEditing');
				}

				var rowMenu;
				function createRowMenu() {
					rowMenu = $('<div/>').appendTo('body');
					rowMenu.menu({
						id : 'rowMenu',
						onClick : function(item) {
							console.log('click menu' + item.text);
						}
					});
					rowMenu.menu('appendItem', {
						text : '刷新',
						name : 'reload',
						iconCls : 'pagination-load',
						onclick : function() {
							$myGrid.datagrid('reload');
						}
					});
					rowMenu.menu('appendItem',
							{
								text : '导出所有数据',
								name : 'exportAll',
								iconCls : 'icon-pageexcel',
								onclick : function() {
									window.location.href = '/grid/export/'
											+ objectCode;
								}
							});
					rowMenu.menu('appendItem', {
						text : '导出本页数据',
						name : 'exportAll',
						iconCls : 'icon-pageexcel',
						onclick : function() {
							// 导出Xls
							$.gridToExcel($myGrid, objectCode);
						}
					});
					if (object.is_celledit) {
						var rowData = {};
						if ($masterGrid) {
							// 获取主表选中行
							var gridSelectRow = $masterGrid
									.datagrid('getSelected');
							if (gridSelectRow) {
								// 初始添加关键字段
								var val = gridSelectRow[config.objectField];
								rowData[config.fields[0]] = val;
								rowData[config.fields[0] + '_val'] = val;
							}
						}

						rowMenu.menu('appendItem', {
							text : '删除行',
							name : 'delete',
							iconCls : 'icon-tabledelete',
							onclick : function() {
								console.log('删除行，索引=' + selectIndex);
								$myGrid.datagrid('deleteRow', selectIndex);
							}
						});
						rowMenu.menu('appendItem', {
							text : '新增行',
							name : 'add',
							iconCls : 'icon-tableadd',
							onclick : function() {
								$myGrid.datagrid('insertRow', {
									index : 0,
									row : rowData
								});
							}
						});
						rowMenu.menu('appendItem', {
							text : '保存数据',
							name : 'save',
							iconCls : 'icon-tablesave',
							onclick : function() {

								var inserted = $myGrid.datagrid('getChanges',
										'inserted');
								var deleted = $myGrid.datagrid('getChanges',
										'deleted');
								var updated = $myGrid.datagrid('getChanges',
										'updated');

								var isOk = true;
								var errorMsg = '';
								if (inserted.length > 0) {
									var json1 = JSON.stringify(inserted);
									console.log('保存add数据' + json1);
									$.syncPost('/grid/add/' + objectCode, {
										rows : json1
									}, function(result, status) {
										if (!result.success) {
											isOk = false;
											errorMsg += result.msg + '<br>';
										}
									});
								}
								if (updated.length > 0) {
									var json3 = JSON.stringify(updated);
									console.log('保存update数据' + json3);
									$.syncPost('/grid/update/' + objectCode, {
										rows : json3
									}, function(result, status) {
										if (!result.success) {
											isOk = false;
											errorMsg += result.msg + '<br>';
										}
									});
								}
								if (deleted.length > 0) {
									var json2 = JSON.stringify(deleted);
									console.log('保存delete数据' + json2);
									$.syncPost('/grid/delete/' + objectCode, {
										rows : json2
									}, function(result, status) {
										if (!result.success) {
											isOk = false;
											errorMsg += result.msg + '<br>';
										}
									});
								}

								if (isOk) {
									$.slideMsg("保存成功！");
									// 确认改动
									$myGrid.datagrid('acceptChanges');
									console.log('标记更改');
								} else {
									$.alert($, errorMsg);
								}
							}
						});
						//            rowMenu.menu('appendItem', {
						//                text: '回滚数据',
						//                name: 'reject',
						//                iconCls: 'icon-undo',
						//                onclick: function () {
						//                    //$myGrid.datagrid('rejectChanges');
						//                    console.log('回滚数据');
						//                }
						//            });
						rowMenu.menu('appendItem', {
							text : '其它功能',
							name : 'other',
							onclick : function() {
								alert('Eova is So Easy');
							}
						});
					}
				}

				var cmenu;
				function createColumnMenu() {
					cmenu = $('<div/>').appendTo('body');
					// 初始化菜单
					cmenu.menu();
					cmenu.menu('appendItem', {
						text : '编辑元字段',
						name : 'editmeta',
						iconCls : 'icon-tableedit',
						onclick : function() {
							window.open('/meta/edit/' + objectCode);
						}
					});
					cmenu.menu('appendItem', {
						text : '编辑元对象',
						name : 'editmeta',
						iconCls : 'icon-tableedit',
						onclick : function() {
							loadDialog($myGrid, '修改元对象',
									'/form/update/eova_object_code-'
											+ object.id);
						}
					});
					// 动态加载列作为菜单项目
					cmenu.menu('appendItem', {
						text : 'other',
						name : 'other',
						iconCls : ''
					});
				}

				if (object.is_celledit) {
					// validator init
					var $form = $('#findGrid').parent();// get datagrid-view dom is validata zone
					$form.validator({
						debug : false,
						stopOnError : true,
						focusInvalid : false,
						showOk : false,
						timely : 0,
						msgMaker : false,
						fields : validators
					});
					$form.on("validation", $.validation);
				}
				//    var pager = $myGrid.datagrid('getPager');
				//    pager.pagination({
				//        buttons: [
				//            {
				//                iconCls: 'icon-tableadd',
				//                handler: function () {
				//                    $myGrid.datagrid('insertRow', {
				//                        index: 0,
				//                        row: {}
				//                    });
				//                }
				//            },
				//            {
				//                iconCls: 'icon-tabledelete',
				//                handler: function () {
				//                    alert('tabledelete');
				//                }
				//            },
				//            {
				//                iconCls: 'icon-tablesave',
				//                handler: function () {
				//                    alert('save');
				//                }
				//            }
				//        ]
				//    });

			});
		</script>
	</div>
	<script>
		var $findGrid = $('#findGrid');

		$(function() {
			//绑定双击事件
			$findGrid.datagrid({
				onDblClickRow : function(rowIndex, rowData) {
					// 模拟点击确认
					parent.$('#find_ok').trigger('click');
				}
			});
		});

		var object = JSON.parse('{"biz_intercept":null,"cn":"title","code":"meta_template",\
			"data_source":"main","default_order":null,"diy_card":null,"diy_js":null,\
			"filter":null,"id":1,"is_celledit":false,"is_first_load":true,"is_show_num":true,\
			"is_single":true,"name":"","pk_name":"id","table_name":"eova_template","view_name":null}');

		var selectData = function($dialog, findBox) {
			//路径
			//console.log("attachment_name=[" + findBox.$attachment_name.val() + "]")
			
			var rows = $findGrid.datagrid('getSelections');
			try {
				// 有选中行
				var oldValue = findBox.$valuebox.val();
				console.log("findBox....");
				console.log(findBox);
				
				var newValue = '';
				var path = '';
				if (rows.length != "0") {
					var vals = [], txts = [];
					for (var i = 0; i < rows.length; i++) { //组成一个字符串，ID主键用逗号隔开
						vals.push(rows[i][object.pk_name]);
						txts.push(rows[i][object.cn]);
						console.log(rows[i].brchcd);
					}
					path = rows[0].brchcd + '\\' + rows[0].file_year + '\\';
					console.log(path);

					// 获取主键值(第一列)
					findBox.$valuebox.val(vals.join(','));
					// 获取翻译值(第二列)
					findBox.$textbox.val(txts.join(','));
					newValue = findBox.$valuebox.val();
					
				} else {
					// 没选值，就清空
					findBox.$valuebox.val("");
					findBox.$textbox.val("");
				}
				
				//todo lipan:此处功能没有实现，有空再想办法
				var $path = $(":root").find('input[name=path]');
				console.log($path.val());
				$path.val(path);
				console.log($path.val());
				
				// 值变更回调
				if (oldValue != newValue) {
					console.log(oldValue + '|' + newValue);
					console.log(findBox.$dom);
					//需要将路径进行回调
					findBox.options.onChange.call(findBox.$dom, oldValue,
							newValue);
					
					
				}
			} catch (err) {
				console.log("查找框validate异常:" + err);
			} finally {
				// 关闭Dialog
				$dialog.dialog('destroy');
			}
		};
	</script>
</body>

<%}%>
